<?php
require '/config.php';
require '/include.php';

$catMenu = catMenu();

// Header Cache infomation
header('Content-Type: text/html; charset=UTF-8');
header('Expires: ' . EXPRIRES);
header('Last-Modified: ' . EXPRIRES);
header("Cache-Control: private, must-revalidate");
header('Cache-Control: max-age=' . MAXAGE);

// For navigation
$limit = category_limit;
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$start = ($page - 1) * $limit;
if ($start < 0)
	$start = 0;

$page_num = '';
if ($page > 1)
	$page_num = sprintf($lang['page_num'], $page);

// Get value from url
$keyword = $urltag = isset($_GET['keyword']) ? strval($_GET['keyword']) : NULL;
if ($keyword) {
	$sth = array('-', '_');
	$keyword = strtolower($keyword);
	$keyword = str_replace($sth, ' ', $keyword);

	$smarty->assign('keyword', $keyword);
	$smarty->assign('search_result_title', sprintf($lang['search_result'], $keyword));

	// page status
	$status = true;

	// total games like $keyword
	$sql = 'SELECT g.g_id
			FROM games g
			WHERE g.active = 1 AND g_name LIKE "%' . $keyword . '%"';
	$total = $db->numRows($sql);

	$panigation = panigation($total, $limit, $page, control_search . $urltag, 1, true);

	if ($total > $limit)
		$smarty->assign('panigation', $panigation);

	// Games
	$Qry = 'SELECT g_name, g_url, images
			FROM games
			WHERE active = 1 AND g_name LIKE "%' . $keyword . '%"
			ORDER BY g_id DESC
			LIMIT ' . $start . ',' . $limit;
	$result = $db->fetchAll($Qry);

	$listgames = array();
	foreach ($result as $key=>$value){
		$imgpath = DC_ROOT . '/data/uploads/' . $value['images'];

		if ($value['images'] && file_exists($imgpath))
			$value['images'] = '/data/uploads/' . $value['images'];
		else
			$value['images'] = '/static.jpg';

		$listgames[] = $value;
	}

	$smarty->assign('listgames', $listgames);
} else {
	$status = false;
}

// Option
$smarty->assign('is_home', true);
$smarty->assign('itemprop', true);
$smarty->assign('status', $status);

$smarty->assign('page_title', sprintf($lang['search_result_title'], $keyword));
$smarty->assign('page_keywords', $keyword . ', ' . $lang['page_keywords']);
$smarty->assign('page_description', $keyword . ' game. ' . $lang['page_description']);
$smarty->assign('image_src', BASE_URL . 'static/img/chipgames.jpg');
$smarty->assign('base_url', rtrim(BASE_URL, '/') . $_SERVER['REQUEST_URI']);

// display theme using smarty
$smarty->display(SKIN . '/search.tpl');